<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form
        label-width="140px"
        ref="formRef"
        :model="searchValue"
        class="flex flex-wrap"
        v-if="infoShowList && infoShowList.length"
      >
        <el-col :span="6" v-if="infoShowList[17]?.query">
          <el-form-item label="数据标准" prop="template">
            <el-select
              v-model="searchValue.template"
              clearable
              placeholder="请选择数据标准"
              filterable
              @change="templateChange"
            >
              <el-option
                v-for="(template, templateIndex) in templateList"
                :key="templateIndex"
                :label="template.dataStandardName"
                :value="template.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[0].query">
          <el-form-item label="资产id" prop="id">
            <ns-input v-model="searchValue.id" clearable placeholder="请输入资产id" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[1].query">
          <el-form-item label="字段名称" prop="column">
            <ns-input v-model="searchValue.column" clearable placeholder="请输入字段名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[2].query">
          <el-form-item label="字段描述" prop="comment">
            <ns-input v-model="searchValue.comment" clearable placeholder="请输入字段描述" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[3].query">
          <el-form-item label="所属表" prop="table">
            <ns-input v-model="searchValue.table" clearable placeholder="请输入所属表" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[4].query">
          <el-form-item label="所属库" prop="database">
            <ns-input v-model="searchValue.database" clearable placeholder="请输入所属库" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[5].query">
          <el-form-item label="资产IP" prop="ip">
            <ns-input v-model="searchValue.ip" clearable placeholder="请输入资产IP" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[6].query">
          <el-form-item label="资产类型" prop="assetType">
            <el-select v-model="searchValue.assetType" clearable placeholder="请选择资产类型">
              <el-option
                v-for="item in assetTypeList"
                :label="item.showName"
                :key="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[7].query">
          <el-form-item label="数据源名称" prop="dataSourceName">
            <ns-input
              v-model="searchValue.dataSourceName"
              clearable
              placeholder="请输入数据源名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[8].query">
          <el-form-item label="数据源类型" prop="datasourceTypeName">
            <ns-input
              v-model="searchValue.datasourceTypeName"
              clearable
              placeholder="请输入数据源类型"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[9].query">
          <el-form-item label="归属机构" prop="deptId">
            <el-cascader
              v-model="searchValue.deptId"
              clearable
              placeholder="请选择归属机构"
              :options="options"
              :props="cascaderProps"
              filterable
              :filter-method="sysFilterMethod"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[10].query">
          <el-form-item label="归属系统" prop="sysId">
            <el-cascader
              v-model="searchValue.sysId"
              placeholder="请选择归属系统"
              :props="systemCascaderProps"
              :options="systemList"
              filterable
              clearable
              :filter-method="sysFilterMethod"
          /></el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[11].query">
          <el-form-item label="分类" prop="classification">
            <el-cascader
              v-model="searchValue.classification"
              placeholder="请选择分类"
              :props="classificationCascaderProps"
              :options="classificationList"
              filterable
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[12].query">
          <el-form-item label="分级" prop="level">
            <el-select v-model="searchValue.level" clearable placeholder="请选择分级">
              <el-option
                v-for="(level, levelIndex) in levelList"
                :key="levelIndex"
                :label="level.levelName"
                :value="level.levelCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[13].query">
          <el-form-item label="保密期限" prop="institutionFiled3">
            <ns-input
              v-model="searchValue.institutionFiled3"
              clearable
              placeholder="请选择保密期限"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[14].query">
          <el-form-item label="定密日期" prop="filed1Range">
            <el-date-picker
              style="width: 90%"
              v-model="searchValue.filed1Range"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD"
              time-format="hh:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[15].query">
          <el-form-item label="解密日期" prop="filed2Range">
            <el-date-picker
              style="width: 90%"
              v-model="searchValue.filed2Range"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD"
              time-format="hh:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[16]?.query">
          <el-form-item label="到期后变更等级" prop="deadlineLevel">
            <el-select
              v-model="searchValue.deadlineLevel"
              clearable
              placeholder="请选择到期后变更等级"
            >
              <el-option
                v-for="(level, levelIndex) in levelList"
                :key="levelIndex"
                :label="level.levelName"
                :value="level.levelCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[18]?.query">
          <el-form-item label="创建时间" prop="auditApplyTime">
            <el-date-picker
              style="width: 90%"
              v-model="searchValue.auditApplyTime"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD"
              time-format="hh:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[19]?.query">
          <el-form-item label="审核状态" prop="auditStatus">
            <el-select v-model="searchValue.auditStatus" clearable placeholder="请选择到审核状态">
              <el-option label="变更审核中" :value="1" />
              <el-option label="审核通过" :value="2" />
              <el-option label="变更审核拒绝" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[20]?.query">
          <el-form-item label="出境批次" prop="batchNum">
            <ns-input placeholder="请输入出境批次" clearable v-model="searchValue.batchNum" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否已分级">
            <el-select v-model="searchValue.isLevel" clearable placeholder="请选择是否已分级">
              <el-option label="已分级" :value="true" />
              <el-option label="未分级" :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否查询关联标准" prop="isSearchSon">
            <el-select
              v-model="searchValue.isSearchSon"
              clearable
              placeholder="请选择是否查询关联标准"
            >
              <el-option label="是" :value="true" />
              <el-option label="否" :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <el-row>
        <el-col :span="24" class="text-right">
          <el-button @click="searchReset" plain>重置</el-button>
          <el-button @click="search" plain>搜索</el-button>
        </el-col>
      </el-row>
    </ContentWrap>
    <ContentWrap>
      <el-form-item>
        <el-button
          type="primary"
          :disabled="ids.length == 0"
          @click="handleUpdateList"
          v-hasPermi="[`assetManage:database:columnMatchEdit${typeName}`]"
        >
          批量修改
        </el-button>
        <el-button
          type="primary"
          :disabled="ids.length == 0"
          @click="handleDeleteList"
          v-hasPermi="[`assetManage:database:columnMatchEdit${typeName}`]"
        >
          批量删除
        </el-button>
        <el-button
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="[`assetManage:database:columnExport${typeName}`]"
          >导出</el-button
        >
        <el-button
          @click="handleEditInfo"
          v-hasPermi="[`assetManage:database:columnShowInfo${typeName}`]"
          >信息展示设置</el-button
        >
        <el-button
          @click="handleAddNum"
          v-hasPermi="[`assetManage:database:columnAddBatchNum${typeName}`]"
          >添加批次号</el-button
        >
      </el-form-item>
      <AsyncTable
        v-bind="tableInfo"
        ref="tableRef"
        :fetchData="fetchData"
        @selection-change="changeTable"
      />
    </ContentWrap>
    <InfoShow ref="dialogRef" @success="getInfoShowConf" />
    <!-- 批量修改弹窗 -->
    <UpdateListLevel ref="updateListRef" @success="search" type="outside" />
    <AddBatchNum v-if="dialogVisible" :dialogVisible="dialogVisible" @close="closeDialog" />
  </div>
</template>

<script setup lang="tsx">
import { getSimpleSystemList } from '@/api/asset/taskManage'
import {
  assetMessagePassDelete,
  assetMessagePassBatchDelete,
  assetMessagePassUpdateBatchNum,
  assetPassExportExcel,
  getDataBasePassList
} from '@/api/assetPass/index'
import * as api from '@/api/dataSourceManage/index'
import { dataClassificationTree } from '@/api/dataStandards/classification/index'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import * as infoShowApi from '@/api/infoShow/index'
import { levelPage } from '@/api/strategyManage/level/index'
import { getSimpleDeptList } from '@/api/system/dept'
import AsyncTable from '@/components/AsyncTable'
import { renderClassification, renderLevel } from '@/utils/commonRender'
import download from '@/utils/download'
import { checkPermi } from '@/utils/permission'
import { sysFilterMethod } from '@/utils/selectFilter'
import { handleTree } from '@/utils/tree'
import UpdateListLevel from '@/views/asset/assetList/databaseList/detail/components/updateListLevel.vue'
import InfoShow from '@/views/assetManage/components/infoShow.vue'
import { Hide, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AddBatchNum from '../components/AddBatchNum.vue'
const route = useRoute()
const dialogVisible = ref(false)
const routeName = ref(route.name)
const systemList = ref([])
const typeName = ref(routeName.value == 'importantDatabase' ? 'Import' : 'Public')
const tableRef = ref()
const formRef = ref()
const { proxy } = getCurrentInstance() as any
const router = useRouter()
const ids = ref<string[]>([])
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'text',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const options = ref<Tree[]>([])
const assetTypeList = ref([])
/**
 * @description: 选取列表时获取列表id
 * @param {*} val
 */
const changeTable = (val) => {
  ids.value = []
  val.map((item) => {
    ids.value.push(item.id)
  })
}
const searchReset = () => {
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const searchValue = ref({
  id: '',
  column: '',
  comment: '',
  table: '',
  database: '',
  ip: '',
  assetType: '',
  dataSourceName: '',
  datasourceTypeName: '',
  deptId: '',
  sysId: '',
  classification: '',
  level: '',
  template: '',
  isSearchSon: '',
  institutionFiled3: '',
  filed2Range: [],
  filed1Range: [],
  deadlineLevel: '',
  isLevel: ''
})
const allSelect = ref(false)

const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const handleShowIp = (row) => {
  row.isShowIp = !row?.isShowIp
}
const tableInfo = reactive({
  columns: [
    {
      type: 'selection',
      selectable: checkSelectable
    },
    {
      label: '资产id',
      prop: 'id',
      width: '200px'
    },
    {
      label: '字段名称',
      render: ({ row }) => {
        return (
          <>
            <el-button
              link
              type="primary"
              onClick={() => {
                openDetail(row)
              }}
            >
              {row.column}
            </el-button>
          </>
        )
      },
      width: '150px'
    },
    {
      label: '字段描述',
      prop: 'comment',
      width: '150px'
    },
    {
      label: '所属表',
      prop: 'table'
    },
    {
      label: '所属库',
      prop: 'database'
    },
    {
      label: '资产IP:端口',
      width: '170px',
      render: ({ row }) => {
        return (
          <>
            <div style="display:flex;align-items:center;justify-content:space-between;">
              {row?.isShowIp ? (
                <span>{row.port ? row.ip + ':' + row.port : row.ip}</span>
              ) : (
                <span style="font-size:17px">***********</span>
              )}
              {row?.isShowIp ? (
                <el-icon>
                  <Hide onClick={() => handleShowIp(row)} />
                </el-icon>
              ) : (
                <el-icon>
                  <View onClick={() => handleShowIp(row)} />
                </el-icon>
              )}
            </div>
          </>
        )
      }
    },
    {
      label: '数据库类型',
      width: '100px',
      render({ row }) {
        return (
          <>
            <span>{row.assetTypeName || row.assetType}</span>
          </>
        )
      }
    },

    {
      label: '数据源名称',
      prop: 'dataSourceName',
      width: '120px'
    },
    {
      label: '数据源类型',
      prop: 'datasourceTypeName',
      width: '120px'
    },
    {
      label: '数据标准',
      prop: 'templateName',
      width: '100px'
    },
    {
      label: '归属机构',
      width: '100px',
      prop: 'deptName'
    },
    {
      label: '归属系统',
      width: '100px',
      prop: 'sysName'
    },
    {
      label: '分类',
      render: (row) => {
        return renderClassification(row, false)
      },
      width: '150px'
    },
    {
      label: '分级',
      render: (row) => renderLevel(row, false),
      width: '150px'
    },
    {
      label: '保密期限',
      width: '100px',
      prop: 'institutionFiled3'
    },
    {
      label: '定密日期',
      prop: 'field1',
      width: '200px'
    },
    {
      label: '解密日期',
      prop: 'field2',
      width: '200px'
    },
    {
      label: '到期后变更等级',
      prop: 'deadlineLevelName',
      width: '150px'
    },
    {
      label: '出境批次',
      prop: 'batchNum',
      width: '150px'
    },
    {
      label: '创建时间',
      prop: 'auditApplyTime',
      width: '300px'
    },
    {
      label: '审核状态',
      width: '110px',
      render: ({ row }) => {
        const showStatusText =
          row.auditStatus == 1 ? '变更审核中' : row.auditStatus == 3 ? '变更审核拒绝' : '审核通过'
        return (
          <>
            <span>{showStatusText}</span>
          </>
        )
      }
    },
    {
      label: '操作项',
      width: '250px',
      fixed: 'right',
      render: ({ row }) => {
        return (
          <>
            {checkPermi([`assetManage:database:columnView${typeName.value}`]) && (
              <el-button
                link
                type="primary"
                onClick={() => {
                  openDetail(row)
                }}
              >
                查看
              </el-button>
            )}
            {checkPermi([`assetManage:database:columnEdit${typeName.value}`]) &&
              row.auditStatus !== '1' && (
                <el-button
                  link
                  type="primary"
                  onClick={() => {
                    handleEdit(row)
                  }}
                >
                  编辑
                </el-button>
              )}
            {checkPermi([`assetManage:database:columnHistory${typeName.value}`]) && (
              <el-button
                link
                type="primary"
                onClick={() => {
                  handleHistory(row)
                }}
              >
                历史记录
              </el-button>
            )}
            {checkPermi([`assetManage:database:columnDelete${typeName.value}`]) &&
              row.auditStatus !== '1' && (
                <ns-button
                  link
                  type="danger"
                  style="margin-left:6px"
                  confirm
                  onClick={() => {
                    handleDelete(row)
                  }}
                >
                  删除
                </ns-button>
              )}
          </>
        )
      }
    }
  ],
  data: []
})

function checkSelectable(row) {
  return row.auditStatus != '1'
}

const handleAddNum = () => {
  dialogVisible.value = true
}

const closeDialog = async (v) => {
  if (v) {
    const { code } = await assetMessagePassUpdateBatchNum({
      ids: ids.value,
      batchNumNew: v,
      dataType: 'column',
      importance: routeName.value == 'importantDatabase' ? '重要数据' : '公开数据',
      ...searchValue.value
    })
    if (code == 200) {
      ElMessage.success('操作成功')
      search()
    }
  }
  dialogVisible.value = false
}

const allSelectHandle = () => {
  allSelect.value = !allSelect.value
  tableRef.value.ignorePageSelect(allSelect.value)
}

//根据数据标准筛选分类
const templateChange = () => {
  if (searchValue.value.template) {
    classificationList.value = classificationListCopy.value.filter(
      (item) => item.id == searchValue.value.template
    )
    searchValue.value.classification = ''
  } else {
    classificationList.value = classificationListCopy.value
  }
}

const pageParams = ref({
  page: 1,
  pageSize: 10
})
const fetchData = async ({ page, pageSize }) => {
  pageParams.value = {
    page,
    pageSize
  }
  const { data, count } = await getDataBasePassList({
    page,
    pageSize,
    dataType: 'column',
    importance: routeName.value == 'importantDatabase' ? '重要数据' : '公开数据',
    ...searchValue.value,
    language: location.href.indexOf('/en/') >= 0 ? 'en' : ''
  })
  return { data, count }
}

const message = useMessage() // 消息弹窗
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await assetPassExportExcel({
      ...pageParams.value,
      dataType: 'column',
      importance: routeName.value == 'importantDatabase' ? '重要数据' : '公开数据',
      ...searchValue.value,
      ids: ids.value,
      language: location.href.indexOf('/en/') >= 0 ? 'en' : ''
    })
    download.excel(data, '资产导出结果.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 批量修改
const updateListRef = ref()
const handleUpdateList = () => {
  updateListRef.value.open(ids.value, 'showAudit', 'importAsset')
}

const openDetail = (row) => {
  // console.log('row', row)
  proxy?.$Drawer({
    params: {
      ...row,
      type: row.handClassificationName ? `人工` : row.classificationName ? `自动` : '--',
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `查看分类分级详情`,
    size: '40%',
    component: import('@/views/assetManage/components/baseInfo.vue')
  })
}

const handleEdit = (row) => {
  proxy?.$Drawer({
    params: {
      ...row,
      type: row.handClassificationName ? `人工` : row.classificationName ? `自动` : '--',
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `编辑`,
    size: '40%',
    component: import('@/views/assetManage/components/editForm.vue')
  })
}

const handleHistory = (row) => {
  router.push({
    path: '/assetManage/fileHistory',
    query: {
      id: row.id,
      dataType: 'column',
      isFormAssetManage: 1
    }
  })
}
const handleDelete = (row) => {
  assetMessagePassDelete(row.id).then((response) => {
    console.log('response', response)
    tableRef.value.fetchData()
    ElMessage.success('操作成功')
  })
}
const handleDeleteList = () => {
  assetMessagePassBatchDelete({ids: ids.value}).then((response) => {
    console.log('response', response)
    tableRef.value.fetchData()
    ElMessage.success('操作成功')
  })
}

/** 添加/修改操作 */
const dialogRef = ref()
const handleEditInfo = () => {
  const type = routeName.value == 'importantDatabase' ? '1' : '7'
  dialogRef.value.open(type)
}

// 获取信息展示
const infoShowList = ref()
const getInfoShowConf = async (type) => {
  const data = await infoShowApi.infoShowList({
    type: routeName.value == 'importantDatabase' ? '1' : '7',
    language: location.href.indexOf('/en/') >= 0 ? 'en' : ''
  })
  infoShowList.value = data
  data.forEach((item, index) => {
    tableInfo.columns[index + 1].hide = item.show === 0 ? true : false
  })
}

const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  options.value = data
}
const getAssetType = async () => {
  const data = await api.getAssetTypeList({ datasourceType: 1 })
  assetTypeList.value = data
}

const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  console.log('data', data)
  levelList.value = data
}
const templateList = ref([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({ page: 1, pageSize: 999, type: 1, status: '1' })
  console.log('data', data)
  templateList.value = data
}

// 分类下拉
const classificationList = ref([])
const classificationListCopy = ref([])
const getClassificationList = async () => {
  const data = await dataClassificationTree({ type: 1 })
  classificationList.value = traverseTree(data)
  classificationListCopy.value = traverseTree(data)
}

function traverseTree(data) {
  const updatedTree = []
  for (let i = 0; i < data.length; i++) {
    const node = data[i] // 创建新节点并添加 disable 属性
    if (node.pid == '-1') {
      node.disabled = true
    }
    updatedTree.push(node)
    if (node.children && node.children.length > 0) {
      node.children = traverseTree(node.children) // 递归遍历子节点并更新子树结构
    }
  }
  return updatedTree
}

onMounted(() => {
  getSystemList()
  getDeptList()
  getAssetType()
  getLevelList()
  getTemplateList()
  getClassificationList()
  getInfoShowConf()
})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
